SEGMENT_BITS = 0x7f
CONTINUE_BIT = 0x80


def var_int(value):
    res = bytearray()

    while True:
        if value & ~SEGMENT_BITS == 0:
            res.append(value)
            return res

        res.append(value & SEGMENT_BITS | CONTINUE_BIT)

        value >>= 7
    
    return res


def read_var_int(bytes):
    value = 0
    position = 0
    bytes_read = 0
    
    for current_byte in bytes:
        value |= (current_byte & SEGMENT_BITS) << position
        bytes_read += 1

        if (current_byte & CONTINUE_BIT) == 0: break
        
        position += 7
    
#    print(f"read_var_int: read {bytes_read} bytes, value {value}")
    return value, bytes_read


def string(s):
    res = bytearray()
    res += var_int(len(s))
    res += bytearray(s, encoding="utf-8")

    return res


def read_string(bytes):
    size, offset = read_var_int(bytes)
    bytes_read = size + offset
#    print(f"read_string: string length {size}, total length {bytes_read}")
    return bytes[offset:offset+size].decode("utf-8"), bytes_read